package org.su.generalmvc.render;

import org.su.generalmvc.IModel;
import org.su.generalmvc.json.JsonHelper;
import org.su.generalmvc.validate.Errors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class JsonExceptionRender implements IRender {
	protected static final Log logger = LogFactory.getLog(JsonExceptionRender.class);

	@Override
	public void render(IModel model, Object result,  String defaultPath, ServletRequest request,
                       ServletResponse response) {
		try {
			//Map<String, Object> model = new HashMap<String, Object>();
			//model.put("data", ret);
			//model.put("success", false);
			
			String info = result.toString();//HtmlHelper.generateHtml(model.getModel(), "pages/exception.vm");
			PrintWriter out = response.getWriter();
			model = new Errors();
			model.addError("操作失败");
			model.addData("exception", info);
			
			out.write(JsonHelper.createJson(model.getModel()));
			out.flush();
			out.close();
		} catch (JsonGenerationException e) {
			logger.error(e);
		} catch (JsonMappingException e) {
			logger.error(e);
		} catch (IOException e) {
			logger.error(e);
		}
	}

}
